<template>
  <view class="container">
    <view class="form-container">
      <!-- 关联宠物 -->
      <view class="form-item">
        <text class="form-label">关联宠物</text>
        <view class="pet-display">
          <text class="pet-name">{{selectedPetName || '未选择宠物'}}</text>
        </view>
      </view>

      <!-- 提醒类型 -->
      <view class="form-item">
        <text class="form-label">提醒类型<text class="required">*</text></text>
        <picker 
          mode="selector" 
          :range="typeOptions" 
          range-key="label"
          @change="onTypeChange"
          :value="typeIndex"
          class="picker"
        >
          <view class="picker-text">{{formData.type || '请选择提醒类型'}}</view>
        </picker>
      </view>

      <!-- 提醒标题 -->
      <view class="form-item">
        <text class="form-label">提醒标题<text class="required">*</text></text>
        <input 
          v-model="formData.title" 
          placeholder="请输入提醒标题"
          class="form-input"
        />
      </view>

      <!-- 提醒时间 -->
      <view class="form-item">
        <text class="form-label">提醒时间<text class="required">*</text></text>
        <picker 
          mode="date" 
          @change="onDateChange"
          class="picker"
        >
          <view class="picker-text">{{formData.displayReminderTime || '请选择提醒时间'}}</view>
        </picker>
      </view>

      <!-- 重复类型 -->
      <view class="form-item">
        <text class="form-label">重复类型</text>
        <picker 
          :value="repeatIndex" 
          :range="repeatTypeLabels" 
          @change="onRepeatChange"
          class="picker"
        >
          <view class="picker-text">{{selectedRepeatType || '不重复'}}</view>
        </picker>
      </view>

      <!-- 是否启用 -->
      <view class="form-item">
        <text class="form-label">是否启用</text>
        <switch 
          :checked="formData.isEnabled" 
          @change="onEnabledChange"
          color="#007AFF"
        />
      </view>

      <!-- 备注 -->
      <view class="form-item">
        <text class="form-label">备注</text>
        <textarea 
          v-model="formData.remark" 
          placeholder="请输入备注信息"
          class="textarea"
          maxlength="200"
        />
      </view>

        <!-- 保存按钮 -->
      <button class="submit-btn" @click="saveRecord">保存修改</button>
    </view>
  </view>
</template>

<script>
import { API_BASE } from '@/config/config.js'
import { getUserId } from '@/utils/auth.js'
import { getPetList } from '@/api/pet.js'
import { getDictData } from '@/api/dict.js'

export default {
  data() {
    return {
      recordId: null,
      healthRecordId: null,
      formData: {
        type: '',
        title: '',
        reminderTime: '',
        displayReminderTime: '', // 用于显示的日期格式
        remark: '',
        petId: null,
        repeatType: '',
        isEnabled: true
      },
      typeOptions: [],
      typeIndex: 0,
      petIndex: 0,
      pets: [],
      repeatTypes: [], // 重复类型字典数据
      repeatTypeLabels: [], // 重复类型标签数组
      repeatIndex: 0 // 默认选择第一个
    }
  },
  watch: {
    // 监听formData.repeatType和repeatTypes的变化，确保选择器正确显示
    'formData.repeatType': {
      handler(newVal) {
        if (newVal !== undefined && this.repeatTypes.length > 0) {
          this.repeatIndex = this.repeatTypes.findIndex(item => item.dictValue === newVal)
          if (this.repeatIndex === -1) this.repeatIndex = 0
          console.log('Watch: Repeat index set to:', this.repeatIndex, 'for repeatType:', newVal);
        }
      },
      immediate: true
    },
    'repeatTypes': {
      handler(newVal) {
        if (newVal.length > 0 && this.formData.repeatType !== undefined) {
          this.repeatIndex = newVal.findIndex(item => item.dictValue === this.formData.repeatType)
          if (this.repeatIndex === -1) this.repeatIndex = 0
          console.log('Watch: Repeat index set to:', this.repeatIndex, 'for repeatType:', this.formData.repeatType);
        }
      },
      immediate: true
    }
  },
  onLoad(options) {
    console.log('Edit page onLoad with options:', options);
    this.recordId = options.id || options.reminderId
    this.healthRecordId = options.healthRecordId
    if (this.recordId) {
      this.loadRecordDetail(this.recordId)
    } else {
      console.error('No record ID provided in options');
      uni.showToast({
        title: '缺少提醒ID',
        icon: 'none'
      });
    }
    this.loadPets()
    this.loadDictData()
  },
  computed: {
    selectedPetName() {
      if (this.formData.petId && this.pets.length > 0) {
        const pet = this.pets.find(p => p.id === this.formData.petId)
        return pet ? pet.name : ''
      }
      return ''
    },
    selectedRepeatType() {
      if (this.formData.repeatType && this.repeatTypes.length > 0) {
        const repeatType = this.repeatTypes.find(r => r.dictValue === this.formData.repeatType)
        return repeatType ? repeatType.dictLabel : '不重复'
      }
      return '不重复'
    },
    selectedStatus() {
      return this.formData.isEnabled ? '1' : '0'
    }
  },
  methods: {
    async loadRecordDetail(recordId) {
      try {
        console.log('Loading record detail for ID:', recordId);
        const response = await uni.request({
          url: `${API_BASE}/system/reminder/${recordId}`,
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          }
        })

        const [error, res] = response
        console.log('API response:', res);
        if (error || !res || res.statusCode !== 200) {
          throw new Error('加载记录失败')
        }

        const recordData = res.data.data || res.data
        console.log('Record data:', recordData);
        console.log('All record keys:', Object.keys(recordData));
        
        // 处理reminderTime，从完整时间格式中提取日期部分用于显示
        let displayReminderTime = ''
        if (recordData.reminderTime && recordData.reminderTime !== '0') {
          displayReminderTime = recordData.reminderTime.substring(0, 10) // 只保留yyyy-MM-dd部分
          // 验证日期格式是否正确
          if (!displayReminderTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
            displayReminderTime = '' // 格式不正确时清空
          }
        }
        
        // 检查字段名，可能API返回的是reminderType而不是type
        const reminderType = recordData.type || recordData.reminderType || recordData.reminder_type;
        const title = recordData.title || recordData.reminderTitle || recordData.reminder_title;
        const reminderTime = recordData.reminderTime || recordData.reminder_time;
        const remark = recordData.remark || recordData.remarks || '';
        
        console.log('Processed fields - type:', reminderType, 'title:', title, 'reminderTime:', reminderTime);
        
        const parsedEnabledValue = this.parseEnabledValue(recordData.isEnabled !== undefined ? recordData.isEnabled : recordData.is_enabled)
        
        this.formData = {
          type: reminderType,
          title: title,
          reminderTime: reminderTime, // 保持完整格式用于提交
          displayReminderTime: displayReminderTime, // 用于显示的日期格式
          remark: remark,
          petId: recordData.petId || null,
          repeatType: recordData.repeatType || recordData.repeat_type || '',
          isEnabled: parsedEnabledValue !== null ? parsedEnabledValue : true // 如果解析结果为null，使用默认值true
        }
        

        
        // 如果有healthRecordId，尝试获取对应的宠物信息
        if (this.healthRecordId) {
          console.log('Health record ID provided:', this.healthRecordId);
          // 这里可以根据healthRecordId加载健康记录信息来获取宠物ID
          // 暂时先记录日志，后续可以根据需要添加API调用
        }

        console.log('Form data after assignment:', this.formData);
        
        // 设置选择器默认值
        this.typeIndex = this.typeOptions.findIndex(item => item.value === this.formData.type)
        console.log('Type index set to:', this.typeIndex);
        
        // 重复类型选择器默认值设置移到loadDictData完成后处理

      } catch (error) {
        console.error('Load record detail error:', error);
        uni.showToast({
          title: '加载记录失败',
          icon: 'none'
        })
      }
    },
    async loadPets() {
      try {
        const userId = getUserId()
        const response = await getPetList(userId)
        
        if (response && response.code === 200) {
          this.pets = response.rows || response.data || []
        }
      } catch (error) {

      }
    },
    async loadDictData() {
      try {
        // 加载记录类型字典
        const typeResponse = await getDictData('pet_health_type')
        if (typeResponse && typeResponse.code === 200) {
          this.typeOptions = typeResponse.data.map(item => ({
            label: item.dictLabel,
            value: item.dictValue
          }))
        }

        // 加载重复类型字典
        const repeatResponse = await getDictData('repeat_type')
        if (repeatResponse && repeatResponse.code === 200) {
          this.repeatTypes = repeatResponse.data
          this.repeatTypeLabels = repeatResponse.data.map(item => item.dictLabel)
          
          // 设置重复类型选择器默认值
          if (this.formData.repeatType !== undefined) {
            this.repeatIndex = this.repeatTypes.findIndex(item => item.dictValue === this.formData.repeatType)
            if (this.repeatIndex === -1) this.repeatIndex = 0 // 如果找不到匹配项，默认选择第一个
            console.log('Repeat index set to:', this.repeatIndex, 'for repeatType:', this.formData.repeatType);
          }
        }

      } catch (error) {
        console.error('加载字典数据失败:', error)
        // 字典数据加载失败时，使用空数组，不提供硬编码默认值
        this.typeOptions = []
        this.repeatTypes = []
        this.repeatTypeLabels = []
      }
    },
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.formData.type = this.typeOptions[this.typeIndex].value
    },
    onDateChange(e) {
      // 将日期格式转换为后端期望的 yyyy-MM-dd HH:mm:ss 格式
      const dateValue = e.detail.value
      if (dateValue) {
        this.formData.reminderTime = dateValue + ' 00:00:00'
        this.formData.displayReminderTime = dateValue // 用于显示的日期格式
      } else {
        this.formData.reminderTime = ''
        this.formData.displayReminderTime = ''
      }
    },
    onPetChange(e) {
      this.petIndex = e.detail.value
      const selectedPet = this.pets[this.petIndex]
      this.formData.petId = selectedPet ? selectedPet.id : null
      console.log('Selected pet:', selectedPet);
    },
    onRepeatChange(e) {
      this.repeatIndex = e.detail.value
      const selectedRepeatType = this.repeatTypes[this.repeatIndex]
      this.formData.repeatType = selectedRepeatType ? selectedRepeatType.dictValue : ''
      console.log('Selected repeat type:', selectedRepeatType);
    },
    onEnabledChange(e) {
      this.formData.isEnabled = e.detail.value
    },
    parseEnabledValue(value) {
      if (value === undefined || value === '') {
        return true // 默认启用
      }
      
      // 如果值为null，保持null让后续逻辑处理
      if (value === null) {
        return null
      }
      
      // 处理布尔值
      if (typeof value === 'boolean') {
        return value
      }
      
      // 处理数字值（1/0）
      if (typeof value === 'number') {
        return value === 1
      }
      
      // 处理字符串值（'1'/'0', 'true'/'false'）
      if (typeof value === 'string') {
        const lowerValue = value.toLowerCase()
        if (lowerValue === '1' || lowerValue === 'true') {
          return true
        }
        if (lowerValue === '0' || lowerValue === 'false') {
          return false
        }
      }
      
      // 其他情况默认返回true
      return true
    },

    async saveRecord() {
      if (!this.formData.type || !this.formData.title || !this.formData.reminderTime) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      try {
        const response = await uni.request({
          url: `${API_BASE}/system/reminder`,
          method: 'PUT',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token'),
            'Content-Type': 'application/json'
          },
          data: {
            id: this.recordId,
            userId: getUserId(), // 添加用户ID
            reminderType: this.formData.type, // 将type映射为reminderType
            title: this.formData.title,
            reminderTime: this.formData.reminderTime,
            displayReminderTime: this.formData.displayReminderTime,
            repeatType: this.formData.repeatType,
            remark: this.formData.remark,
            remarks: this.formData.remark, // 添加remarks字段以兼容API
            isEnabled: this.formData.isEnabled ? '1' : '0'
          }
        })

        const [error, res] = response
        if (error || !res || res.statusCode !== 200) {
          const errorMsg = res?.data?.msg || res?.data?.message || '保存失败'
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
          return
        }
        
        const responseData = res.data
        if (responseData && responseData.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })

          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          const errorMsg = responseData?.msg || responseData?.message || '修改失败'
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
        }
      } catch (error) {

        uni.showToast({
          title: '修改失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.form-item {
    margin-bottom: 30rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
  }

.form-label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  width: 180rpx;
  flex-shrink: 0;
  margin-right: 20rpx;
}

.required {
  color: #e74c3c;
  margin-left: 4rpx;
}

.form-input {
  flex: 1;
  min-height: 36rpx;
  height: 80rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #3498db;
}

.picker {
  flex: 1;
  min-height: 36rpx;
  height: 80rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-sizing: border-box;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.pet-display {
  flex: 1;
  min-height: 36rpx;
  height: 80rpx;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-sizing: border-box;
}

.pet-name {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.textarea {
  flex: 1;
  min-height: 36rpx;
  height: 120rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  resize: vertical;
}

/* 是否启用开关样式 */
   .form-item switch {
     flex-shrink: 0;
     margin-left: 20rpx;
   }

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  margin-top: 40rpx;
  transition: opacity 0.3s;
}

.submit-btn:hover {
  opacity: 0.9;
}
</style>